package org.qrd.openmayyam;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.http.HttpContext;
import org.osgi.service.http.HttpService;
import org.osgi.service.http.NamespaceException;

	/**
	 * Listens for new WAR files at intervals
	 * @author Adarsh
	 * @author Sivaraman
	 */
public class MainThread extends Thread{
	
	/**
	 * Object for the custom class loader
	 */
	ClassLoader cl;
	/**
	 * This is used to get the reference of org.osgi.service.http.HttpService.
	 */
	private HttpService httpService;
	/**
	 * It is used to create a default Http context.
	 */
	private HttpContext httpContext;
    int len,i=0;
    /**
     * context[][] stores the servlets mapping details.
     */
    String contexts[][],wars[];
    File f;
    CustomClassLoader cc = new CustomClassLoader();
	ParseXML parser=new ParseXML();
	ExpandWar expandWar=new ExpandWar();
	HttpServlet hs = null;
	/**
	 * Boolean value that determines whether the bundle has been requested to stop or not
	 */
	
	private boolean running=true;
	BundleContext arg0;
	/**
	 * This assigns the context of the bundle that calls it to the instance of the class.
	 */
	public void run(BundleContext arg0) throws Exception {
		this.arg0=arg0;
	}
	/**
	 * This is the main method that expands all the new WAR files and then parses the web.xml file.
	 * The servlets are registered here.
	 */
	
	public void run() {
		while(running) {
		try {
			// Get the list of all the WAR files present
			
			wars=expandWar.expandAll("/home/adarsh/");
	    	} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	    	// If there are no WAR files, wait for few seconds.
		if(wars==null){
			try {
				Thread.sleep(50000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			continue;
		}
		// Process through each WAR file.
		
	for(i=0;i<wars.length;i++) {
		
		if(wars[i]==null) break;
		
//		System.out.println("wars no : " + i);
		f=new File("/home/adarsh/"+wars[i]+"/WEB-INF/web.xml");
		System.out.println(f.getAbsolutePath());
			try {
				// parse the web.xml file of the currrent WAR file.
				
				contexts=parser.parseXML(f,wars[i]);
			} catch (MalformedURLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

	
	  System.out.println("servlet registered : " + wars[i]);
	// For each entry in the web.xml file, register the servlets.
	  
for(int j=0;j<contexts.length;j++)
{
	// If there are no entries , then break out.
	if(contexts[j][0]==null) break;

	System.out.println("j :" +j);
	// Get the class through a custom class loader, here contexts[j][1] refers to the complete path of the class file 
	// and contexts[i][2] refers to the class name.
	Class cls = cc.getClass(contexts[j][1],contexts[j][2] );
	//Class cls = cc.getClass("/home/adarsh/sample/WEB-INF/classes/mypackage/Hello.class", "mypackage.Hello");
	try {
		// once we have the class, a new instance is to be created.
		hs = (HttpServlet)cls.newInstance();
	} catch (InstantiationException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IllegalAccessException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	// In the next 3 steps, a handle for the httpservice as exposed by the bundle is got. 
	 ServiceReference serviceReference = arg0.getServiceReference("org.osgi.service.http.HttpService");
	 httpService = (HttpService)arg0.getService(serviceReference);
	 httpContext = httpService.createDefaultHttpContext();
	// httpService.registerServlet("/hello", hs, null, httpContext);
	 try {
		 // use the registerservlet method to register the servlets.
		 
		httpService.registerServlet(contexts[j][0], hs, null, httpContext);
	} catch (ServletException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (NamespaceException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
System.out.println("out of first one");
	}
	// once all the WAR files have been parsed , wait for few sec.
	try {
		Thread.sleep(50000);
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
}
	/**
	 * This method is called to stop the thred by setting the boolean value to false.
	 */
	
	public void stopThread(){
		this.running=false;
	}
}

